/**
 * Created by xiangyufang on 2016/10/10.
 */
;(function($,window,document,undefined){
    /***全局变量初始化 start***/
    //表格
    var $table = $('#JQ_table').checkbox3();
    var DTTABLE;
    //任务名称
    var $taskName = $('#JQ_task');
    //工具类型
    var $tool_type;
    //复制任务
    var $copy_content = $("#JQ_copy_content");
    /***全局变量初始化 end***/

    /***表单条件初始化 start***/
    // 管道
    var $pipeline = $('#JQ_pipeline').select3();
    // 管段
    var $segment = $('#JQ_segment').select3({
        title:'管段'
    });
    // 起点位置
    var $begin = $('#JQ_begin').select3({
        title: '起点位置',
        server: true,
        mileType: 'float',
        pigType: 'pig',
        param: {'pipeLineId':$pipeline,'pipeSegmentId':$segment}
    });
    // 终点位置
    var $end = $('#JQ_end').select3({
        title:'终点位置',
        server: true,
        mileType: 'float',
        pigType: 'pig',
        param: {'pipeLineId':$pipeline,'pipeSegmentId':$segment,'beginSignId':$begin}
    });
    // 触发管道
    $pipeline.element.on('select',function(e,v){
        var id = v || $pipeline.val();
        if(id){
            // 管段
            DyyBase.ajax(cleanPipeApi.url_clean_segment(), {pipeLineId:id}, function(dataset){
                if(dataset.bool){
                    var json = DyyBase.getSelect(dataset.result);
                    $segment.add(json);
                }
            });
            // 起点 & 终点
            DyyBase.ajax(cleanPipeApi.url_clean_beginEnd(), {pipeLineId:id}, function(dataset){
                var beginEndData = dataset.result;
                var begin = DyyBase.getNewPos(beginEndData,'begin',true);
                var end = DyyBase.getNewPos(beginEndData,'end',true);
                $begin.asset(begin);
                $end.asset(end);
            });
        }else{
            $segment.add([]);
            $begin.add([]);
            $end.add([]);
        }
    });
    // 触发管段
    $segment.element.on('select',function(e,v){
        var id = v || $segment.val();
        if(id){
            // 起点 & 终点
            DyyBase.ajax(cleanPipeApi.url_clean_beginSegmentEnd(), {pipeSegmentId:id}, function(dataset){
                var beginEndData = dataset.result;
                var begin = DyyBase.getNewPos(beginEndData,'begin',true);
                var end = DyyBase.getNewPos(beginEndData,'end',true);
                $begin.asset(begin);
                $end.asset(end);
            });
        }else{
            $begin.add([]);
            $end.add([]);
        }
    });

    //复制-清管工具
    var $copy_tool = $('#JQ_copy_toolSelect').select3();
    //复制-清管时间
    var $date_copy = $("#JQ_copy_time");
    $date_copy.datetimepicker({
        timepicker: false,
        format:'Y-m-d',
        scrollInput: false,
        style: 'z-index:999'
    });
    /***表单条件初始化 end***/

    //复制框的宽度
    var w_h = $(window).height();
    var w_w = $(window).width();
    var copy_w = $copy_content.width();
    var copy_h = $copy_content.height();
    var top_h = w_h/2 - copy_h/2;
    var left_w = w_w/2 - copy_w/2;
    $copy_content.css({
        "top": top_h,
        "left": left_w
    });

    //**查询条件**
    var filter = {
        //查询条件
        getSearchVal: function(data){
            var filter = {};
            filter.mode = true;
            // 分页参数
            if (data) {
                if (data.start == 0) {
                    filter['jsonBean.pageNum'] = 1;
                } else {
                    filter['jsonBean.pageNum'] = data.start / 10 + 1;
                }
                filter['jsonBean.pageCount'] = data.length;
            }
            //管道参数
            filter.lineId = function(){
                var v = $pipeline.val();
                if(v){
                    return v;
                }
                return '';
            }();
            //起点参数
            filter.beginMile = function(){
                var v = $begin.val('mile');
                if(v){
                    return v;
                }else if(v == 0){
                    return v;
                }
                return '';
            }();
            //终点参数
            filter.endMile = function(){
                var v = $end.val('mile');
                if(v){
                    return v;
                }else if(v == 0){
                    return v;
                }
                return '';
            }();
            //任务名称参数
            filter.taskName = function(){
                var v =$taskName .val();
                if(v){
                    return v;
                }
                return '';
            }();
            return filter;
        },
        getCopyData: function(id,type){
            var filter = {};
            //复制 任务名称参数
            filter.mode = true;
            filter.id = id;
            filter.taskName = function(){
                var v = $("#JQ_copy_name").val();
                if(v != ''){
                    return v;
                }else{
                    $('#JQ_copy_name').TIP({content:'任务名称不能为空！'});
                    filter.mode = false;
                }
                return '';
            }();
            //复制 清管工具参数
            filter.pagTool = function(){
                if(type == true){
                    var sv = $copy_tool.val();
                    if(sv){
                        return sv;
                    }else{
                        $('#JQ_copy_toolSelect').TIP({content:'清管工具不能为空！'});
                        filter.mode = false;
                    }
                }else if(type == false){
                    var iv = $('#JQ_copy_toolInput').val();
                    if(iv){
                        return iv;
                    }else{
                        $('#JQ_copy_toolInput').TIP({content:'清管工具不能为空！'});
                        filter.mode = false;
                    }
                }
            }();
            //复制 清管时间参数
            filter.planPagDateTime = function(){
                var v = $("#JQ_copy_time").val();
                if(v){
                    return v;
                }else{
                    $('#JQ_copy_time').TIP({content:'计划实施时间不能为空！'});
                    filter.mode = false;
                }
            }();
            //复制 备注参数
            filter.createRemark = function(){
                var v = $("#JQ_copy_remark").val();
                if(v){
                    return v;
                }
                return '';
            }();
            return filter;
        },
        //复选框数据选择(数组储存id)
        getCheckData: function(){
            var $checks = $table.find('i.zy-checkbox');
            //数组储存id
             var arr = [];
             $checks.each(function () {
                 var $this = $(this);
                 if ($this.hasClass('active')) {
                     arr.push($this.attr('data-id'));
                 }
             });
             return arr;
        }
    };

    //**表格数据**
    DTTABLE = $table.DataTable({
        'language': {
            'paginate': {
                'next': '下一页',
                'previous': '上一页'
            },
            'info': '本次检索共 _TOTAL_ 条，每页显示 10 条，共 _PAGES_ 页',
            'zeroRecords': DyyBase.table_empty(),
            'infoEmpty': ''
        },
        'autoWidth': false,
        'order': [],
        'serverSide': true,
        'pageLength': 10,
        'ordering': false,
        'processing': false,
        'searching': false,
        'lengthChange': false,
        'ajax': function (data, callback) {
            var param = filter.getSearchVal(data);
            DyyBase.ajax(cleanPipeApi.url_clean_task(), param, function (dataset) {
                $("#JQ_check_all").attr('data-chk', 'false').removeClass('active');
                var returnData = {};
                returnData.draw = data.draw;
                returnData.recordsTotal = dataset.result.total;
                returnData.recordsFiltered = dataset.result.total;
                returnData.data = DyyBase.clearNull(dataset.result.list);
                callback(returnData);
            });
        },
        'drawCallback': function () {
        },
        'columns': [
            {
                data: 'id',
                render: function (data,type,row) {

                    return '<i class="zy-checkbox" data-id="' + data + '" data-status="' + row.staus + '" title="选中"></i>';
                }
            },
            {
                data: 'taskName',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'lineName',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'fromPigName',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'toPigName',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'planPagDateTime',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'createUser',
                render: function (data) {
                    return '<span title="' + data + '">' + data + '</span>';
                }
            },
            {
                data: 'staus',
                render: function (data) {
                    if(data == '3'){
                        return '<span id="'+ data + '"  title="进行中">进行中</span>';
                    }else if(data == '2'){
                        return '<span id="'+ data + '"  title="已发布">已发布</span>';
                    }else if(data == '4'){
                        return '<span id="'+ data + '"  title="已完成">已完成</span>';
                    }else if(data == '1'){
                        return '<span id="'+ data + '"  title="未发布">未发布</span>';
                    }else{
                        return '<span id="'+ data + '"  title="状态未知">状态未知</span>';
                    }
                }
            },
            {
                data: 'id',
                render: function (data,type,row) {
                    return '<i data-a="' + data + '" data-status="' + row.staus + '" class="xyf-edit-icon" title="编辑"></i>';
                }
            },
            {
                data: 'id',
                render: function (data,type,row) {
                    return '<i data-a="' + data + '" data-status="' + row.staus + '" class="xyf-release-icon" title="发布"></i>';
                }
            },
            {
                data: 'id',
                render: function (data,type,row) {
                    return '<i data-a="' + data + '" data-name="'+ row.taskName + '" class="xyf-enclosure-icon" title="附件"></i>';
                }
            }
        ]
    });


    //**查询**
    $('#JQ_search').click(function(){
        var param = filter.getSearchVal();
        if(param.mode){
            if(DTTABLE){
                DTTABLE.draw();
            }
        }
    })

    //关闭复制任务框
    $("#JQ_xyf_close_i").click(function(){
        $("#JQ_copy_task_div").hide();
    });
    //复制
    $("#JQ_task_copy").click(function(){
        var $this = $(this);
        var param = filter.getCheckData();
        if(param.length == 1){
            var taskId = param[0];
            getCopyFormData(taskId);
            $("#JQ_copy_task_div").show();
                                             //点击确认，确认复制任务
            $("#JQ_copy_confirm").click(function(){
                //$("#JQ_copy_task_div").hide();
                submitCopyTask(taskId ,$tool_type);
            });
        }else if(param.length > 1){
            $this.MSG({
                content: '只能勾选一条任务进行复制!'
            });
        }else{
            $this.MSG({
                content: '请选择您要复制的任务!'
            });
        }
    });
    //填充复制选框函数内容函数
    function getCopyFormData(id){
        DyyBase.ajax(cleanPipeApi.url_clean_task_copyData(), {taskId:id}, function(dataset){
            if(dataset.bool){
                var copy_data = dataset.result;
                //填充
                $("#JQ_copy_pipe").text(copy_data.pipeLine. showName);
                $("#JQ_copy_start").text(copy_data.fromVal.name);
                $("#JQ_copy_end").text(copy_data.toVal.name);
                $("#JQ_copy_type").text(copy_data.pagType);
                $("#JQ_copy_set").text(copy_data.fromPig.name);
                $("#JQ_copy_stop").text(copy_data.toPig.name);

                $("#JQ_copy_pipe").attr('title',copy_data.pipeLine. showName);
                $("#JQ_copy_start").attr('title',copy_data.fromVal.name);
                $("#JQ_copy_end").attr('title',copy_data.toVal.name);
                $("#JQ_copy_type").attr('title',copy_data.pagType);
                $("#JQ_copy_set").attr('title',copy_data.fromPig.name);
                $("#JQ_copy_stop").attr('title',copy_data.toPig.name);

                $("#JQ_copy_remark").val(copy_data.task.createRemark);
                $("#JQ_copy_name").val(copy_data.task.taskName);
                $date_copy.val(copy_data.task.planPagDateTime);
                if(copy_data.task.isDropDown == true){
                    $("#JQ_copy_select").show();
                    var tool_id = copy_data.taskToolId;
                    var data = DyyBase.getSelect(copy_data.cleanTool);
                    $copy_tool.add(data).fit(tool_id);
                }else if(copy_data.task.isDropDown == false){
                    $("#JQ_copy_input").show();
                    $("#JQ_copy_toolInput").val(copy_data.taskTool);
                }
                $tool_type = copy_data.task.isDropDown;
            }
        });
    }
    //提交复选框任务
    function submitCopyTask(id ,type){
        var param = filter.getCopyData(id,type);
        if(param.mode){
            DyyBase.ajax(cleanPipeApi.url_clean_task_copySubmit(), param, function(dataset){
                if(dataset.bool){
                    var result = dataset.result;
                    if(result.msgCode == 'fail_taskName'){
                        $('#JQ_copy_name').TIP({content:'任务名称不能相同！'});
                    }else if(result.msgCode == 'success'){
                        $("#JQ_copy_task_div").hide();
                        if(DTTABLE){
                            DTTABLE.draw();
                        }
                    }
                }
            },{async:false});
        }
    }

    //批量删除
    $("#JQ_task_delete").click(function(){
        var $this = $(this);
        var param = filter.getCheckData();
        if(param.length > 0){
            $this.MSG({
                type: 'confirm',
                height: 230,
                content: '您确认要删除选中的任务吗?',
                yesBtnTxt: '确认',
                yesBtnAct: function(){
                    DyyBase.ajax(cleanPipeApi.url_clean_task_delete(),DyyBase.convertToArr({idStr:param}),function(dataset){
                        if(dataset.bool){
                            $this.MSG({
                                type: 'success',
                                content: dataset.message,
                                yesBtnAct: function(){
                                    if(DTTABLE){
                                        DTTABLE.draw();
                                    }
                                }
                            });
                        }else {
                            $this.MSG({
                                type: 'error',
                                content: dataset.message,
                                yesBtnAct: function(){
                                    if(DTTABLE){
                                        DTTABLE.draw();
                                    }
                                }
                            });
                        }
                    });
                }
            });
        }else{
            $this.MSG({
                content: '请选择您要删除的任务!'
            });
        }

    });

    //批量发布
    $("#JQ_task_release").click(function(){
        var $this = $(this);
        var param = filter.getCheckData();
        if(param.length > 0){
            $this.MSG({
                type: 'confirm',
                height: 230,
                content: '您确认要发布选中的任务吗?',
                yesBtnTxt: '确认',
                yesBtnAct: function(){
                    DyyBase.ajax(cleanPipeApi.url_clean_task_release(),DyyBase.convertToArr({idStr:param}),function(dataset){
                        if(dataset.bool){
                            $this.MSG({
                                type: 'success',
                                content: dataset.message,
                                yesBtnAct: function(){
                                    if(DTTABLE){
                                        DTTABLE.draw();
                                    }
                                }
                            });
                        }else {
                            $this.MSG({
                                type: 'error',
                                content: dataset.message,
                                yesBtnAct: function(){
                                    if(DTTABLE){
                                        DTTABLE.draw();
                                    }
                                }
                            });
                        }
                    });
                }
            });
        }else{
            $this.MSG({
                content: '请选择您要发布的任务!'
            });
        }
    });

    //发布
    $table.on("click","i.xyf-release-icon",function(event){
        var $this = $(this);
        var id = $this.attr("data-a");
        var status = $this.attr("data-status");
        var arr = [];
        arr.push(id);
        $this.MSG({
            type: 'confirm',
            height: 230,
            content: '您确认要发布此任务吗?',
            yesBtnTxt: '确认',
            yesBtnAct: function(){
                DyyBase.ajax(cleanPipeApi.url_clean_task_release(),DyyBase.convertToArr({idStr:arr}),function(dataset){
                    if(dataset.bool){
                        $this.MSG({
                            type: 'success',
                            content: dataset.message,
                            yesBtnAct: function(){
                                if(DTTABLE){
                                    DTTABLE.draw();
                                }
                            }
                        });
                    }else {
                        $this.MSG({
                            type: 'error',
                            content: dataset.message,
                            yesBtnAct: function(){
                                if(DTTABLE){
                                    DTTABLE.draw();
                                }
                            }
                        });
                    }
                });
            }
        });
        event.stopPropagation();
    });

    //下载附件
    var $download_form = $('#JQ_download_form');
    $table.on("click","i.xyf-enclosure-icon",function(event){
        var $this = $(this);
        var id = $this.attr("data-a");
        var taskName = $this.attr("data-name");
        $download_form.empty();
        var $input = $('<input type="hidden" name="businessId" value="'+ id + '">');
        var $input2 = $('<input type="hidden" name="downFileName" value="'+ taskName + '的附件">');
        var $input3 = $('<input type="hidden" name="type" value="piggingTaskAtt">');
        $download_form.append($input).append($input2).append($input3);
        $download_form.submit();

        $('#JQ_action_iframe').get(0).onload = function(){
            var content = this.contentWindow.document.body.innerHTML;
            content = $.parseJSON(content);
            if(!content.bool){
                $this.MSG({
                    type: 'error',
                    content: content.result
                });
            }
        };

        event.stopPropagation();
    });

    //新建
    $("#JQ_task_create").click(function(event){
        var url = cleanPipeApi.url_clean_newTask('');
        window.location.href = url;
        event.stopPropagation();
    });

    //编辑
    $table.on("click","i.xyf-edit-icon",function(event){
        var $this = $(this);
        var id = $this.attr("data-a");
        var status = $this.attr("data-status");
        if(status == '2'){
            $this.MSG({
                content: '已发布的任务不能进行修改!'
            });
        }else{
            var url = cleanPipeApi.url_clean_newTask(id);
            window.location.href = url;
        }

        event.stopPropagation();
    });


})(jQuery,window,document);